package com.whutosa.template.server.controller;

import com.alibaba.fastjson.JSON;
import com.whutosa.template.server.model.ChatMsg;
import com.whutosa.template.server.model.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by 19110 on 2016/9/27.
 */
public class ChatWebSocketHandler extends TextWebSocketHandler {

    private static final Logger log = LogManager.getRootLogger();
    private static final Map<User, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User currentUser = (User) session.getAttributes().get("user");

        TextMessage msg = new TextMessage(JSON.toJSONString(new ChatMsg(currentUser, message)));

        log.info(JSON.toJSON(msg));

        Set<User> users = sessions.keySet();
        for (User user : users) {
            if (user.equals(currentUser)) {
                continue;
            }
            WebSocketSession socketSession = sessions.get(user);
            socketSession.sendMessage(msg);
        }

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        User user = (User) session.getAttributes().get("user");
        sessions.put(user, session);
        log.info("connected:" + user.getUid());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User user = (User) session.getAttributes().get("user");
        sessions.remove(user);
    }

}
